<template>
  <view>
    <view class="search-view">
      <uni-search-bar
        radius="100"
        @confirm="onSearch"
        @clear="onClear"></uni-search-bar>
    </view>
    <view class="list-view">
      <radio-group @change="onChange">
        <view class="list-item" v-for="(item, index) in list" :key="index">
          <radio color="#2EB0D9" :value="JSON.stringify(item)"></radio>
          <image :src="item.pictureName"></image>
          <div class="right">
            <div class="top">
              <div class="name">{{ item.nurseName }}</div>
              <div class="phone">{{ item.tel }}</div>
            </div>
            <div class="bottom">{{ item.hospitalName }}</div>
          </div>
        </view>
      </radio-group>
      <uni-load-more :status="status"></uni-load-more>
    </view>
    <view class="bottom-fixed-view">
      <view class="submit-btn" @click="showToDoorTimeDialog">确认派发</view>
    </view>

    <uni-popup ref="toDoorTimeDialog" type="dialog">
      <uni-popup-dialog
        ref="inputClose"
        mode="base"
        title="填写上门时间"
        @confirm="toDoorTimeDialogConfirm">
        <uni-datetime-picker
          :start="dateStart"
          hide-second
          v-model="toDoorTimeDate"
          :border="false"
          @change="toDoorTimeDialogChange">
          <view style="display: flex; align-items: center">
            <uni-icons
              type="calendar"
              size="20"
              style="margin-right: 10rpx"></uni-icons>
            <text v-if="!toDoorTime">请选择时间</text>
            <text>{{ toDoorTime }}</text>
          </view>
        </uni-datetime-picker>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import PageInfo from "../../utils/pageutils";
import * as nurseInfo from "../../common/api/nurseInfo.js";
import * as orderInfo from "../../common/api/orderInfo.js";
export default {
  data() {
    return {
      pageInfo: new PageInfo(),
      list: [],
      status: "more",
      current: null,
      uid: "",
      toDoorTimeDate: "",
      toDoorTime: "",
      form: {
        nurseName: "",
      },
      orderNum: "",
    };
  },
  onLoad(opt) {
    console.log("派发", opt);
    if (opt.uid) {
      this.uid = opt.uid;
      this.orderNum = opt.orderNum;
      console.log("派发订单号", this.orderNum);
    }
    this.refresh();
  },
  onPullDownRefresh() {
    this.refresh();
  },
  onReachBottom() {
    this.loadMore();
  },
  computed: {
    dateStart() {
      return new Date().format("yyyy-MM-dd HH:mm");
    },
  },
  methods: {
    refresh() {
      this.pageInfo.reset();
      this.list = [];
      this.status = "loading";
      this.getList();
    },
    loadMore() {
      if (this.pageInfo.isNotLoadAll) {
        this.status = "loading";
        this.pageInfo.nextPage();
        this.getList();
      } else {
        this.status = "noMore";
      }
    },
    getList() {
      const dataJson = uni.getStorageSync("user_info") || "{}";
      const data = JSON.parse(dataJson) || {};
      const param = {
        pageIndex: this.pageInfo.pageIndex,
        pageSize: this.pageInfo.pageSize,
        hospitalUid: data.hospitalUid,
        ...this.form,
      };
      nurseInfo
        .queryByPage(param)
        .then((result) => {
          const list = result.data.data.rows || [];
          const total = result.data.data.total;
          this.list = [...this.list, ...list];
          this.pageInfo.total = total;
          this.pageInfo.loadedTotal = this.list.length;
          setTimeout(() => {
            if (this.pageInfo.isNotLoadAll) {
              this.status = "more";
            } else {
              this.status = "noMore";
            }
            uni.stopPullDownRefresh();
          }, 200);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    onChange(e) {
      this.current = e.detail.value;
    },
    submit() {
      uni.showModal({
        title: "提示",
        content: "确认提交？",
        success: (res) => {
          if (res.confirm) {
            console.log("用户点击确定");
            const param = {
              uid: this.uid,
              dispatchNursesUid: this.current.uid,
              dispatchNurses: this.current.nurseName,
              nursesPhone: this.current.tel,
              receiveOrderTime: new Date().format("yyyy-MM-dd HH:mm"),
              toDoorTime: this.toDoorTime,
              status: "待出发",
            };
            // console.log(param);
            orderInfo
              .update(param)
              .then((result) => {
                try {
                  const result = uni.request({
                    // url: "https://applet.youtuyiliao.com/api/hsServer/hospitalInfo/updateHospital",
                    url: "http://192.168.1.26:8050/applet/user/nurse/access/nursesMessage",
                    method: "POST",
                    data: {
                      orderNumber: this.orderNum,
                      userId: this.current.uid,
                      templateId: "9COMsyH83_06oiFLX4kgFtj1OeYmAQol9difTNlWgdA",
                    },
                  });
                  console.log("订阅消息发送结果：", result.data);
                  // if (result[1].data.code === 200) {
                  //   // if (result.code === 200) {
                  //   uni.showToast({ title: "消息订阅成功" });
                  // } else {
                  //   uni.showToast({ title: "订阅信息提交失败", icon: "none" });
                  // }
                } catch (error) {
                  console.error("订阅请求失败:", error);
                }
                // uni.navigateBack();
              })
              .catch((error) => {
                console.log(error);
              });
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    },
    showToDoorTimeDialog() {
      if (this.current === null) {
        uni.showToast({
          icon: "none",
          title: "请选择护士",
        });
        return;
      }
      this.current = JSON.parse(this.current);
      this.$refs.toDoorTimeDialog.open();
    },
    toDoorTimeDialogConfirm() {
      if (!this.toDoorTime) {
        uni.showToast({
          title: "请填写上门时间",
          icon: "error",
        });
        return;
      }
      this.submit();
    },
    toDoorTimeDialogChange(e) {
      console.log(e);
      this.toDoorTime = new Date(e).format("yyyy-MM-dd HH") + ":00";
    },
    onSearch(e) {
      console.log(e);
      this.form.nurseName = e.value;
      this.refresh();
    },
    onClear() {
      this.form.nurseName = "";
      this.refresh();
    },
  },
};
</script>

<style lang="scss" scoped>
.list-view {
  width: 100%;
  box-sizing: border-box;
  padding: 10rpx;
  padding-bottom: 80rpx;
}
.list-item {
  width: 100%;
  padding: 20rpx 10rpx;
  box-sizing: border-box;
  background: white;
  display: flex;
  align-items: center;
  margin-top: 10rpx;
  radio {
    transform: scale(0.7);
  }
  image {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
  }
  .right {
    margin-left: 10rpx;
    .top {
      display: flex;
      color: #232323;
      font-size: 30rpx;
      font-weight: bold;
      .name {
      }
      .phone {
        margin-left: 10rpx;
      }
    }
    .bottom {
      color: #232323;
      font-size: 26rpx;
    }
  }
}

.bottom-fixed-view {
  position: fixed;
  bottom: 0;
  background: #f9f9f9;
  width: 100%;
  box-sizing: border-box;
  padding: 10rpx;
  .submit-btn {
    background: #2eb0d9;
    color: white;
    width: 100%;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 40rpx;
  }
}

.search-view {
  background: white;
}
</style>
